package ru.st.selenium.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;



import ru.st.selenium.model.Film;

public class MainPage extends AnyPage {

	public MainPage(PageManager pages) {
		super(pages);
	}

	@FindBy(xpath = "//div[@class='title']")
	private List<WebElement> filmTitleList;

	@FindBy (id = "q")
	private WebElement searchField;
	
	@FindBy(css = "div.content")
	private WebElement divWithErrorMessage;
	
	public List<Film> getFilms() {
		wait.until(refreshed(visibilityOfAllElementsLocatedBy(By.xpath("//div[@class='title']"))));
		List<Film> filmList = new ArrayList<Film>();
		for (WebElement el : filmTitleList) {
			String title = el.getText();
			filmList.add(new Film().setTitle(title));
		}
		return filmList;
	}
	
	public FilmPage selectFilmByIndex(int index){
		filmTitleList.get(index).click();
		return pages.filmPage;
	}
	
	public FilmPage selectFilm(Film film){
		for (WebElement el : filmTitleList) {
			if (el.getText().equals(film.getTitle())) {
				el.click();	
				break;
			}
		}
		return pages.filmPage;
	}
	
	public String getTitleFilm() {
		return filmTitleList.get(0).getText();
	}	
	
	public MainPage search(String value){
		wait.until(presenceOfAllElementsLocatedBy(By.cssSelector("div#results a")));
		searchField.clear();
		searchField.sendKeys(value + Keys.RETURN);
		return pages.mainPage;
	}
	
	public MainPage cleanSearchField(){
		searchField.clear();
		searchField.sendKeys(Keys.RETURN);
		return pages.mainPage;
	}
	
	public String  getErrorMessage(){
		return  divWithErrorMessage.getText();
	}

	public MainPage ensurePageLoaded() {
		super.ensurePageLoaded();
		wait.until(presenceOfElementLocated(By.cssSelector("div#results")));
		return this;
	}

}
